package cn.livingCloud.service.impl.operation;

import cn.livingCloud.context.BeanProvider;
import cn.livingCloud.context.VelocityFactory;
import cn.livingCloud.dto.MemberDto;
import cn.livingCloud.entity.content.AbstractReplyContent;
import cn.livingCloud.entity.user.Member;
import cn.livingCloud.repository.MemberMapper;
import cn.livingCloud.wechat.protocol.req.AbstractReqMsg;
import cn.livingCloud.wechat.protocol.resp.AbstractRespMsg;
import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.VelocityEngine;

import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 唐旭 on 2016/1/14.
 */
public class RespMsgConverter {
    private transient MemberMapper mapper = BeanProvider.getBean(MemberMapper.class);
    private AbstractReplyContent content;
    private AbstractReqMsg textMsg;

    public RespMsgConverter(AbstractReplyContent content, AbstractReqMsg textMsg) {
        this.content = content;
        this.textMsg = textMsg;
    }

    public AbstractRespMsg convert() {
        Member member = mapper.findMemberByOpenid(textMsg.getFromUserName());
        if (member == null) {
            return null;
        }
        List<String> stringList = content.getReplyContent();
        List<String> result = parseContent(member, stringList);
        content.setContent(result);

        AbstractRespMsg abstractRespMsg = content.toAbstractRespMsg();
        abstractRespMsg.load(textMsg);
        return abstractRespMsg;
    }

    private List<String> parseContent(Member member, List<String> stringList) {
        MemberDto memberDto = new MemberDto(member);
        VelocityEngine engine = VelocityFactory.getEngine();
        VelocityContext context = new VelocityContext();
        StringWriter writer = new StringWriter();
        context.put("member", memberDto);
        List<String> result = new ArrayList<>(stringList.size());

        for (String item : stringList) {
            engine.evaluate(context, writer, "", item);
            result.add(writer.toString());
        }
        return result;
    }
}
